package com.xy.core.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.xy.common.upload.FileRepository;
import com.xy.common.util.DictUtils;
import com.xy.common.web.FrontUtils;
import com.xy.core.web.WebErrors;
import com.xy.p2p.action.front.TmemberAction;
import com.xy.p2p.model.Timageinfo;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.service.TimageinfoService;
import com.xy.p2p.service.TmemberService;

@Controller
public class FileUploadAction {
	private static final Logger log = LoggerFactory.getLogger(FileUploadAction.class);
	private static String uploadPath_pre = "/upload";

	//会员头像上传
	@RequestMapping("/imageUpload.jspx")
	public String imageUpload(String filename, Integer uploadNum, Boolean mark, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request, ModelMap model)
	throws Exception
	{
		WebErrors errors = validateUpload(file, request);
		if (errors.hasErrors()) {
			model.addAttribute("error", errors.getErrors().get(0));
			return "content/attachment_iframe";
		}
		String origName = file.getOriginalFilename();
		String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
		// TODO 检查允许上传的后缀
		if(!"jpg".equals(ext)&&!"png".equals(ext)&&!"jpeg".equals(ext)&&!"gif".equals(ext)){
			throw new Exception("上传的图片类型不支持.");
		}
		//
		try {
			FileRepository fr=	new FileRepository();
			fr.setServletContext(request.getSession().getServletContext());
			String fileUrl = fr.storeByExt(uploadPath_pre, ext, file);
			// 加上部署路径
			Tmember tmember = (Tmember) request.getSession().getAttribute(TmemberAction.AUTH_KEY);
			tmember.setHeadurl(fileUrl);
			tmemberService.save(tmember);
			String ctx = request.getContextPath();
			fileUrl = ctx + fileUrl;
			model.addAttribute("uploadPath", fileUrl);
			model.addAttribute("uploadNum", uploadNum);

		} catch (IllegalStateException e) {
			model.addAttribute("error", e.getMessage());
			log.error("upload file error!", e);
		} catch (IOException e) {
			model.addAttribute("error", e.getMessage());
			log.error("upload file error!", e);
		}
		return "/common/iframe_upload.html";
	}
	
	
	
	

	//用户资料上传
	@RequestMapping("/member/infoUpload.jspx")
	public String infoUpload(HttpServletResponse response,String captcha,String filename, Integer uploadNum, Boolean mark, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request, ModelMap model)
	throws Exception
	{
		try {
		Tmember tmember = (Tmember) request.getSession().getAttribute(TmemberAction.AUTH_KEY);
		
		WebErrors errors = validateUpload(file, request);
		if (errors.hasErrors()) {
			model.addAttribute("error", errors.getErrors().get(0));
			return "content/attachment_iframe";
		}
		String origName = file.getOriginalFilename();
		String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
		// TODO 检查允许上传的后缀
		if(!"jpg".equals(ext)&&!"png".equals(ext)&&!"jpeg".equals(ext)&&!"gif".equals(ext)){
			throw new Exception("上传的图片类型不支持.");
		}
		//
			FileRepository fr=	new FileRepository();
			fr.setServletContext(request.getSession().getServletContext());
			String fileUrl = fr.storeByExt(uploadPath_pre, ext, file);
			// 加上部署路径
//			tmember.setHeadurl(fileUrl);
//			tmemberService.save(tmember);
			Timageinfo timageinfo = new Timageinfo(tmember,fileUrl,origName.substring(0, origName.lastIndexOf('.')),null,0);
			timageinfoService.save(timageinfo);
			
			String ctx = request.getContextPath();
			fileUrl = ctx + fileUrl;
			model.addAttribute("uploadPath", fileUrl);
			model.addAttribute("uploadNum", uploadNum);

		} catch (IllegalStateException e) {
			model.addAttribute("error", e.getMessage());
			log.error("upload file error!", e);
		} catch (IOException e) {
			model.addAttribute("error", e.getMessage());
			log.error("upload file error!", e);
		}
//		return "/common/iframe_upload.html";
		return "redirect:/member/v_timageinfoupdoad.jspx";
	}
	
	
	private WebErrors validateUpload(MultipartFile file, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNull(file, "file")) {
			return errors;
		}
		
		return errors;
	}

	@Resource
	private TmemberService tmemberService;
	@Resource
	private TimageinfoService timageinfoService;
	@Resource
	private ImageCaptchaService imageCaptchaService;
}